<!--
  * 公共应用表
  *
  * @Author:    zhoujk
  * @Date:      2025-01-26 06:40:44
-->
<template>
  <a-modal :width="1200" title="商家授权" :open="openForm" @cancel="onClose" :maskClosable="false" :destroyOnClose="true" :footer="false">
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item label="商家名称" class="smart-query-form-item">
          <CustomSelect
            v-model:value="queryForm.merchantId"
            :placeholder="'请选择商家名称'"
            :api="merchantApi.page"
            :dropdownMatchSelectWidth="false"
            queryParamKey="companyNameLeftLike"
            labelField="companyName,no"
          />
          <!-- <a-input style="width: 200px" v-model:value="queryForm.appName" placeholder="商家名称" allow-clear /> -->
        </a-form-item>
        <a-form-item class="smart-query-form-item">
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery" class="smart-margin-left10">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card size="small" :bordered="false" :hoverable="false">
      <!---------- 表格操作行 begin ----------->
      <a-row class="smart-table-btn-block">
        <div class="smart-table-operate-block">数据列表</div>
        <div class="smart-table-setting-block">
          <a-button @click="handleAdd" type="primary" class="mr-2" size="small">
            <template #icon>
              <PlusOutlined />
            </template>
            添加商家授权
          </a-button>
          <!-- <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.OPERATION.MERCHANT" :refresh="queryData" /> -->
        </div>
      </a-row>
      <!---------- 表格操作行 end ----------->

      <!---------- 表格 begin ----------->
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false">
        <template #bodyCell="{ record, column }">
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <!--<a-button @click="showForm(record)" type="link">编辑</a-button>-->
              <a-button @click="showDetail(record, 'updata')" type="link">修改</a-button>
              <a-button @click="delAuth(record)" type="link">删除</a-button>
              <a-button @click="showDetail(record, 'view')" type="link">详情</a-button>
            </div>
          </template>
        </template>
      </a-table>
      <!---------- 表格 end ----------->

      <div class="smart-query-table-page">
        <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="queryForm.pageSize"
          v-model:current="queryForm.pageNo"
          v-model:pageSize="queryForm.pageSize"
          :total="total"
          @change="queryData"
          @showSizeChange="queryData"
          :show-total="(total) => `共${total}条`"
        />
      </div>
    </a-card>

    <appAuthForm v-model:open="appAuthOptions.open" :formType="appAuthOptions.formType" :rowData="appAuthOptions.rowData" @ok="queryData" />
  </a-modal>
</template>
<script setup>
  import { reactive, ref, onMounted, getCurrentInstance, computed, watch } from 'vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { message, Modal } from 'ant-design-vue'
  import { appAuthPage, appAuthDelete } from '/@/api/business/b-operation/merchant-app/app-auth-api'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import appAuthForm from './app-auth-form.vue'
  import { merchantApi } from '/@/api/business/b-operation/merchant/merchant-api'
  import { isEmpty } from 'lodash'
  import { selectDictLabel, strToArr } from '/@/utils/common'
  import {
    AUTH_APP, //授权产品，产品列表
    APP_TYPE, ///应用类型
  } from '/@/constants/dict'

  const { proxy } = getCurrentInstance()

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      required: true,
      default: () => {},
    },
  })
  const emit = defineEmits(['update:open'])
  const openForm = computed({ get: () => props.open, set: (val) => emit('update:open', val) })
  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '序号',
      dataIndex: 'index',
      customRender: ({ index, record }) => {
        return (queryForm.pageNo - 1) * queryForm.pageSize + index + 1
      },
    },
    {
      title: '商家授权应用名称',
      dataIndex: 'appName',
      ellipsis: true,
    },
    {
      title: '商家名称',
      dataIndex: 'companyName',
      ellipsis: true,
    },
    {
      title: '应用类型',
      dataIndex: 'appType',
      customRender: ({ text }) => {
        return selectDictLabel(APP_TYPE, text)
      },
      ellipsis: true,
    },
    {
      title: '授权token',
      dataIndex: 'appAuthToken',
      ellipsis: true,
    },
    {
      title: '授权产品',
      dataIndex: 'authApp',
      customRender: ({ text }) => {
        let arr = strToArr(text)
        let names = arr.map((item) => selectDictLabel(AUTH_APP, item))
        return names.toString()
      },
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 180,
    },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    merchantId: undefined, //商家id
    applicationId: computed(() => props.rowData?.id), //商家应用id
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      let queryResult = await appAuthPage(queryForm)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  // onMounted(queryData)

  /* 删除授权 */

  // 删除
  async function delAuth(record) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除该数据吗?',
      okText: '删除',
      okType: 'danger',
      async onOk() {
        rowDelete(record)
      },
      cancelText: '取消',
      onCancel() {},
    })
  }

  //请求删除
  async function rowDelete(record) {
    try {
      SmartLoading.show()
      await appAuthDelete({ id: record.id })
      message.success('删除成功')
      queryData()
    } catch (e) {
      console.log(e)
      smartSentry.captureError(e)
    } finally {
      SmartLoading.hide()
    }
  }

  /* 关闭弹窗 */

  function onClose() {
    openForm.value = false
  }

  /* 授权表单 */
  const appAuthOptions = ref({
    open: false,
    formType: 'add',
    rowData: undefined,
  })
  function handleAdd() {
    appAuthOptions.value = { open: true, formType: 'add', rowData: { applicationId: props.rowData.id } }
  }
  function showDetail(data, type) {
    appAuthOptions.value = { open: true, formType: type, rowData: data }
  }
  /* 授权表单 */

  watch(
    [() => openForm.value, () => props.rowData],
    (val) => {
      if (val[0] && val[1]) {
        queryData()
      }
    },
    { immediate: true },
  )
</script>
